<?php

namespace app\worker\controller;

use app\common\model\mysql\OrderProductNormal;
use app\common\model\mysql\OrderProductWater;
use app\common\model\mysql\OrderTask;
use app\common\model\mysql\OrderTicket;
use app\common\model\mysql\Send;
use app\common\model\mysql\Order;
use app\common\model\mysql\WarehouseSpaceProduct;

class Statistics extends AuthBase
{
    /**
     * 本次配送统计
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function distributionStatistics(){
        // 公共查询条件
        $commonConditions = [
            ['worker_id_send','=',$this->workerId],
            ['company_id','=',$this->companyId],
            ['stateenum','in',[2,4,8,64]],
            ['ordertypeenum','=',1],
            ['isdel','=','0'],
        ];
        $sendWhere = [
            ['worker_id_send','=',$this->workerId],
            ['company_id','=',$this->companyId],
            ['isdel','=','0'],
        ];
        $orderSendRes = (new Send())->getSendFind($sendWhere);
        if($orderSendRes){
            switch ($orderSendRes['stateenum']) {
                case 2:
                case 4:
                case 8:
                    $commonConditions[] = ['send_id','=',$orderSendRes['send_id']];
                    break; // 添加break来阻止代码继续执行到下一个case
                case 16:
                case 32:
                    $commonConditions[] = ['send_id','=',0];
                    break; // 添加break来阻止代码继续执行到下一个case
            }
        }
        $orderIdArr = (new Order())->getNormalOrderFiledArr($commonConditions,'order_id');
        if($orderIdArr){
            $orderWhere = [
                ['order_id','in',$orderIdArr],
            ];
            // 送水统计
            $field = "product_id,product_name,sellcount_real as sellcount";
            $orderProductWater  = (new OrderProductWater())->getNormalOrderProductWater($orderWhere,$field);
            // 使用关联数组按 product_id 合并数据
            $productSales = [];
            foreach ($orderProductWater as $data) {
                $productId = $data['product_id'];
                if (!isset($productSales[$productId])) {
                    $productSales[$productId] = $data;
                } else {
                    $productSales[$productId]['sellcount'] += $data['sellcount'];
                }
            }
            // 转换数据格式并准备存储
            $formattedItems = [];
            foreach ($productSales as $product) {
                $formattedItems[] = [
                    'product_id'    => (string)$product['product_id'],
                    'product_name'  => (string)$product['product_name'],
                    'sellcount'     => (string)$product['sellcount'],
                    'saveGoods'     => []  // 初始化 saveGoods 数组
                ];
            }
            // 获取仓库空间产品信息并填充到对应项中
            foreach ($formattedItems as &$item) {
                $warehouseConditions = [
                    ['a.product_id', '=', $item['product_id']],
                    ['a.isdel', '=', '0'],
                ];
                $warehouseFields = "a.warehouse_space_product_id, a.warehouse_id, a.warehouse_space_id, b.warehouse_name, c.warehouse_space_name, a.tcount";
                $item['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList($warehouseConditions, $warehouseFields);
            }
            unset($item);  // 断开引用
            // 送水票统计
            $field = "ticket_id,count_give,count_cost,ticket_name";
            $ticketData = (new OrderTicket())->getNormalOrderTicket($orderWhere,$field);
            // 使用关联数组按 ticket_id 合并数据并构建最终数组结构
            $ticketStatistics = [];
            foreach ($ticketData as $data) {
                $ticketId = $data['ticket_id'];
                if (!isset($ticketStatistics[$ticketId])) {
                    // 初始化数组元素，包括 ticket_name 和计数累加器
                    $ticketStatistics[$ticketId] = [
                        'ticket_name'  => $data['ticket_name'],
                        'count_cost'   => 0,
                        'count_give'   => 0,
                    ];
                }
                // 累加计数
                $ticketStatistics[$ticketId]['count_cost'] += $data['count_cost'];
                $ticketStatistics[$ticketId]['count_give'] += $data['count_give'];
            }

            // 将关联数组转换为索引数组（如果需要的话）
            $ticketStatisticsArray = array_values($ticketStatistics);
            // 任务统计
            $field = "order_task_id,tname,tmoney";
            $taskData = (new OrderTask())->getNormalOrderTask($orderWhere,$field);
            // 普通商品统计
            $field = "product_id,product_name,sellcount";
            $productData = (new OrderProductNormal())->getNormalOrderProductNormal($orderWhere,$field);
            if($productData){
                foreach ($productData as $key=>$value){
                    $WarehouseWhere = [
                        ['a.product_id','=',$value['product_id']],
                        ['a.isdel','=','0'],
                    ];
                    $field = "a.warehouse_space_product_id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount";
                    $productData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList($WarehouseWhere,$field);
                }
            }
        }
        $data = array(
            'waterData'     => $formattedItems??[],
            'productData'   => $productData??[],
            'ticketData'    => $ticketStatisticsArray??[],
            'taskData'      => $taskData??[],
        );
        return show(config('status.success'), "本次配送统计", $data);
    }
}
